import { Handlers, PageProps } from "$fresh/server.ts";
import {
  CredentialMeta,
  GetCredit,
  UpdateCredential,
} from "~/denokv/resume.ts";
import { deepMerge } from "deepmerge";

import dayjs from "dayjs";
import { ResumeCTX } from "~/routes/resume/_middleware.ts";
import { ResumeTimeLine } from "~/islands/resume/timeline.tsx";
import Blogs from "./(_components)/RepositoryBlog.tsx";
import { getLogger } from "logger";
import { UserInfo } from "~/types.ts";
const dl = getLogger();
export const handler: Handlers<
  UserInfo,
  ResumeCTX
> = {
  async GET(_, ctx) {
    const resp = await ctx.render(ctx.state.userInfo);
    return resp;
  },
  /**
   * 通过authing云提交过来的认证信息
   * @param req
   * @param context
   * @returns
   */
  async POST(req) {
    const form = await req.formData();

    const ac = form.get("access_token") as string;
    const state = form.get("state") as string;
    const expires_in = form.get("expires_in") as string;
    // const code = form.get("code");
    // const token_type = form.get("token_type");
    // const scope = form.get("scope");
    dl.info(
      "接收到认证服务回调信息:" +
        JSON.stringify(Object.fromEntries(form.entries())),
    );
    const record = await GetCredit(state);
    if (!record) {
      dl.info("接收到认证服务回调,但未查询到凭据:" + state);
      return new Response(null, {
        status: 302,
        headers: {
          location: "/",
        },
      });
    }
    const { ok } = await UpdateCredential(deepMerge(record, {
      id: state as string,
      duration: Number.parseInt(expires_in ?? "0"),
      accessToken: ac as string,
    } as CredentialMeta));
    if (!ok) {
      dl.info("接收到认证服务回调,但更新凭据失败:" + state);
      return new Response(null, {
        status: 302,
        headers: {
          location: "/",
        },
      });
    }

    const urlObj = new URL(req.url);
    urlObj.pathname = "/resume";
    urlObj.searchParams.set("st", state as string); // 传入临时state,不直接暴露access_token
    const location = urlObj.toString();
    dl.info("已更新凭据,重定向至:" + location);
    return new Response(null, {
      status: 302,
      headers: {
        location,
      },
    });
  },
};

export default ((
  ctx: PageProps<
    UserInfo,
    ResumeCTX
  >,
) => {
  const createAt = dayjs(ctx.state.createAt);
  const current = dayjs();
  const diffInfo = current.diff(createAt, "second"); // current.subtract(createAt)

  return (
    <div class="py-1 px-12 mx-auto max-w-6xl  xl:w-3/5 md:w-4/5 text-black dark:text-[#ddd] xs:px-4">
      <Blogs />
      <div class="text-center font-bold xs:mt-8 mt-20">
        <h4 class="xs:my-6 my-12 text-4xl xs:text-2xl">
          {
            /* {ctx.state.corporateName
            ? `${ctx.state.corporateName}:`
            : ""} */
          }你好,我叫
        </h4>
        <h1 class="xs:text-5xl xl:text-9xl md:text-7xl delay-300  mt-12 mb-8 ">
          <span class="ease-in transition-all hover:tracking-widest">
            {ctx.data.name}
          </span>
        </h1>
        <h4 class="text-2xl xs:text-xl">一名前端开发工程师</h4>
      </div>

      {/* 介绍信息 */}
      <div class="text-center xs:mt-8 mt-20   text-xl md:text-2xl xl:text-3xl xl:leading-loose tracking-widest ">
        <p>
          一个喜欢没事就研究新兴技术的coder,到目前为止,大部分工作为编写管理后台,
          偶尔也会写点前端小玩意儿,比如
          <a
            class="inline-block bg-slate-300 dark:bg-zinc-900 px-2 leading-tight rounded-md mx-2 hover:cursor-zoom-in hover:underline decoration-orange-400 "
            href="https://jsr.io/@advanced/fetcher"
          >
            <code>@advanced/fetcher</code>
          </a>
          <a
            class="inline-block  bg-slate-300 dark:bg-zinc-900 px-2 leading-tight rounded-md mx-2 hover:cursor-zoom-in hover:underline decoration-orange-400"
            href="https://jsr.io/@advanced/crypto"
          >
            <code>@advanced/crypto</code>
          </a>
        </p>
        <p class="my-6">
          除此以外,还喜欢搞linux或者docker,推崇devops,有它会让我的工作更轻松又从容.
        </p>
      </div>
      {/* 工作时间线 */}
      <h4 class="text-center mt-40 mb-20 font-bold text-2xl">工作经历</h4>
      <div class="px-4">
        <ResumeTimeLine />
      </div>
      <div class="text-center xs:mt-8 mt-20  xl:text-3xl xs:text-xl leading-loose tracking-widest">
        {/* 未来 */}
        <p>
          未来,如若有机会从事web3d方向,会优先考虑.如果3d方向发现不适合,就做web全栈吧~
        </p>

        <div class="my-20">
          {/* text-sm */}

          <p class="text-xs text-green-400 dark:text-zinc-600 mt-4 ">
            链接剩余有效时间(小时):{((ctx.state.duration - diffInfo) / 60 /
              60)
              .toFixed(
                2,
              )}
          </p>
        </div>
      </div>
    </div>
  );
});
